
module.exports = {
    /**
     * 随机整数
     */
    randomInt(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }

        return min + Math.floor(Math.random() * (max - min + 1));
    },
    random(min, max, digits = 0) {
        return +(min + Math.random() * (max - min)).toFixed(digits);
    },

    loadPrefab(path, callback) {
        cc.loader.loadRes(path, (err, prefab) => {
            if (err) {
                cc.error(`Load prefab error: ${err}`);
                return;
            }

            let newPrefab = cc.instantiate(prefab);
            callback(newPrefab);
        });
    },

    /* Async tasks */
    series: function (tasks, completeCallback) {
        let done = function () {
            let task = tasks.shift();
            if (task) task(done);
            else completeCallback();
        };
        done();
    },

    /* Timer */
    delayFrameTime: function (frameNumber, callback) {
        let frameNum = 1;
        let scheduler = cc.director.getScheduler();
        let frameCallback = function () {
            if (frameNum++ !== frameNumber) return;

            scheduler.unschedule(frameCallback, this);

            callback();
        };
        scheduler.schedule(frameCallback, new cc.Node(), 0, cc.REPEAT_FOREVER, 0);
    },


    showBorder(node, color = cc.Color.BLACK, gNode) {
        let box;
        let handler = () => {
            if (!gNode) {
                gNode = new cc.Node();
                gNode.parent = cc.director.getScene();
            } else {
                cc.pIn(box, gNode.convertToNodeSpace( cc.p(box) ));
            }
        };

        if (node instanceof cc.Rect) {
            box = node;
            handler();
        } else if (gNode === node.parent) {
            box = node.getBoundingBox();
            cc.pAddIn(box, cc.pCompMult( gNode.getAnchorPoint(), cc.pFromSize( gNode.getContentSize() ) ));
        } else {
            box = node.getBoundingBoxToWorld();
            handler();
        }

        let ctx = gNode.getComponent(cc.Graphics) || gNode.addComponent(cc.Graphics);

        ctx.rect(box.x, box.y, box.width, box.height);

        if (color instanceof cc.Color) {
            ctx.strokeColor = color;
            ctx.lineWidth = 3;
        } else {
            ctx.strokeColor = color.color;
            ctx.lineWidth = color.width;
        }

        ctx.stroke();
    }
};
